package cn.yl.pay.service.task;

import cn.yl.api.server.result.Result;
import cn.yl.pay.service.config.WechatPayConfig;
import cn.yl.pay.service.service.feign.UserCourseOrderFeignService;
import com.github.wxpay.sdk.WXPay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WxPayTask {
    @Autowired
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private UserCourseOrderFeignService userCourseOrderFeignService;
    // (cron = "30 10 * * * ?") 每小时的10分30秒触发任务
    @Scheduled(cron = "30 10 * * * ?")
    public void taskCheckOrderTimeOut(){
        log.info(" taskCheckOrderTimeOut 开始执行");
        List<String> timeOutOrderIdList = userCourseOrderFeignService.timeOutOrderIdList(120);
        if(timeOutOrderIdList !=null){
            timeOutOrderIdList.forEach(orderId -> {
                log.info("超时订单Id orderId= "+orderId);
                //todo 拿到 orderId 再去微信查一下 看是否支付成功，如果成功 则修改 status 为 2 否则超时 修改为 -1
                WXPay wxpay = new WXPay(wechatPayConfig);
                Map<String, String> data = new HashMap<String, String>();
                data.put("out_trade_no", orderId);
                try {
                    Map<String, String> resultMap = wxpay.orderQuery(data);
                    if (resultMap.get("trade_state").equalsIgnoreCase("success")) {
                        userCourseOrderFeignService.updateByStatus(orderId,2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                userCourseOrderFeignService.updateByStatus(orderId,-1);
            });
        }
    }
}
